<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"/>
    <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
    <title>扫码日志监控</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
            background-color: #f9f9f9;
            position: relative;
        }

        /* ===== 修改：右上角复合计数器 ===== */
        #counter-display {
            position: fixed;
            top: 20px;
            right: 20px;
            text-align: center;
            z-index: 1000;
        }

        #total-count {
            background-color: #e74c3c;
            color: white;
            font-size: 28px;
            font-weight: bold;
            padding: 8px 16px;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
        }

        #unique-count {
            color: #7f8c8d;
            font-size: 14px;
            margin-top: 6px;
        }

        #current-barcode-count {
            color: #27ae60;
            font-size: 13px;
            margin-top: 4px;
            font-weight: bold;
        }

        h1 {
            color: #2c3e50;
        }

        #trigger-btn {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        #trigger-btn:hover {
            background-color: #2980b9;
        }

        #trigger-btn:disabled {
            background-color: #bdc3c7;
            cursor: not-allowed;
        }

        .status {
            margin: 10px 0;
            font-size: 14px;
            color: #7f8c8d;
        }

        #log-container {
            margin-top: 20px;
            max-width: 800px;
            background: white;
            border: 1px solid #ecf0f1;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .log-item {
            padding: 12px;
            border-bottom: 1px solid #eee;
            position: relative;
        }

        .log-item.duplicate {
            background-color: #fdf2f2;
            border-left: 4px solid #e74c3c;
        }

        .duplicate-warning {
            color: #e74c3c;
            font-weight: bold;
            margin-top: 4px;
            font-size: 13px;
        }

        .log-item:last-child {
            border-bottom: none;
        }

        .log-time {
            font-size: 12px;
            color: #95a5a6;
            margin-bottom: 4px;
        }

        .log-base {
            font-weight: bold;
            color: #2c3e50;
        }

        .log-barcodes {
            margin-top: 6px;
            padding-left: 20px;
        }

        .log-barcode {
            display: inline-block;
            background: #e0f7fa;
            color: #006064;
            padding: 2px 8px;
            margin: 2px;
            border-radius: 4px;
            font-size: 13px;
        }
    </style>
</head>
<body>
<!-- ===== 修改：替换为复合计数器 ===== -->
<div id="counter-display">
    <div id="total-count">0</div>
    <div id="unique-count">(唯一: 0)</div>
    <div id="current-barcode-count">[本次: 0 个码]</div>
</div>

<h1>扫码日志监控</h1>

<button id="trigger-btn" onclick="triggerScan()">触发扫码</button>
<div class="status" id="status">WebSocket: 连接中...</div>

<div id="log-container"></div>

<script>
    const logContainer = document.getElementById('log-container');
    const statusEl = document.getElementById('status');
    const triggerBtn = document.getElementById('trigger-btn');
    // ===== 修改：引用新元素 =====
    const totalCountEl = document.getElementById('total-count');
    const uniqueCountEl = document.getElementById('unique-count');
    const currentBarcodeCountEl = document.getElementById('current-barcode-count');

    // 用于去重：记录已扫过的基板编号
    const scannedBasePlates = new Set();
    let totalScanCount = 0;      // 每次扫码消息 +1
    let uniquePlateCount = 0;    // 唯一基板数

    const wsUrl = 'ws://localhost:7778/ws/scan-logs';
    let ws = null;

    function connectWebSocket() {
        ws = new WebSocket(wsUrl);

        ws.onopen = () => {
            statusEl.textContent = '✅ WebSocket 已连接';
            statusEl.style.color = '#27ae60';
        };

        ws.onmessage = (event) => {
            try {
                const log = JSON.parse(event.data);
                addLogToPage(log);
            } catch (e) {
                console.error('解析消息失败:', e);
                addRawLog(event.data);
            }
        };

        ws.onclose = () => {
            statusEl.textContent = '⚠️ WebSocket 已断开（5秒后重连）';
            statusEl.style.color = '#e74c3c';
            setTimeout(connectWebSocket, 5000);
        };

        ws.onerror = (error) => {
            console.error('WebSocket 错误:', error);
            statusEl.textContent = '❌ WebSocket 连接出错';
        };
    }

    function addLogToPage(log) {
        // ✅ 总扫码次数 +1（每次收到消息都加）
        totalScanCount++;
        totalCountEl.textContent = totalScanCount;

        const basePlateNo = log.basePlateNo || 'N/A';
        const isDuplicate = scannedBasePlates.has(basePlateNo);

        if (!isDuplicate) {
            scannedBasePlates.add(basePlateNo);
            uniquePlateCount = scannedBasePlates.size;
            uniqueCountEl.textContent = `(唯一: ${uniquePlateCount})`;
        }

        // ✅ 计算本次扫码的产品条码数量
        const barcodes = Array.isArray(log.productBarcode)
            ? log.productBarcode
            : (log.productBarcode ? [log.productBarcode] : []);
        const currentCount = barcodes.length;
        currentBarcodeCountEl.textContent = `[本次: ${currentCount} 个码]`;

        // 渲染日志项
        const item = document.createElement('div');
        item.className = 'log-item';
        if (isDuplicate) {
            item.classList.add('duplicate');
        }

        const timeEl = document.createElement('div');
        timeEl.className = 'log-time';
        timeEl.textContent = `[${log.time || new Date().toLocaleString()}]`;

        const baseEl = document.createElement('div');
        baseEl.className = 'log-base';
        baseEl.textContent = `基板编号: ${basePlateNo}`;

        const barcodesEl = document.createElement('div');
        barcodesEl.className = 'log-barcodes';
        barcodesEl.innerHTML = '<strong>关联产品条码:</strong>';

        barcodes.forEach(barcode => {
            const span = document.createElement('span');
            span.className = 'log-barcode';
            span.textContent = barcode;
            barcodesEl.appendChild(span);
        });

        if (isDuplicate) {
            const warnEl = document.createElement('div');
            warnEl.className = 'duplicate-warning';
            warnEl.textContent = '⚠️ 该基板已扫码，重复记录！';
            item.appendChild(warnEl);
        }

        item.appendChild(timeEl);
        item.appendChild(baseEl);
        item.appendChild(barcodesEl);

        logContainer.insertBefore(item, logContainer.firstChild);
    }

    function addRawLog(text) {
        const div = document.createElement('div');
        div.style.color = '#e74c3c';
        div.textContent = `[原始消息] ${text}`;
        logContainer.insertBefore(div, logContainer.firstChild);
    }

    async function triggerScan() {
        triggerBtn.disabled = true;
        triggerBtn.textContent = '触发中...';

        try {
            const response = await fetch('http://localhost:7778/scanner/trigger-scan', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    basePlateNo: 'BP-' + Date.now(),
                    productBarcode: ['PROD-' + Date.now(), 'PROD-' + (Date.now() + 1)]
                })
            });

            if (response.ok) {
                console.log('触发扫码成功');
            } else {
                alert('触发失败: ' + response.status);
            }
        } catch (error) {
            console.error('触发扫码失败:', error);
            alert('网络错误: ' + error.message);
        } finally {
            triggerBtn.disabled = false;
            triggerBtn.textContent = '触发扫码';
        }
    }

    window.addEventListener('load', () => {
        connectWebSocket();
    });
</script>
</body>
</html>